package pers.hl.module_main.explore

import pers.hl.common.base.BaseViewModel
import pers.hl.common.base.SingleLiveEvent
import pers.hl.lib_global.model.bean.Book
import pers.hl.lib_global.model.bean.BookTag

class ExploreViewModel : BaseViewModel<ExploreRepo>() {

    private val tagsData = SingleLiveEvent<List<BookTag>>()
    private val topBooksData = SingleLiveEvent<List<Book>>()

    /**
     * 获取所有标签
     */
    fun loadTags(): SingleLiveEvent<List<BookTag>> {
        launchOnIO {
            val result = mModel.getBookTags()
            val tags = result.data
            if (tags.isEmpty()) {
                return@launchOnIO
            }
            for (tag in tags) {
                loadBooksByTagId(tag)
            }
            tagsData.postValue(tags)
        }
        return tagsData
    }

    /**
     * 根据标签id获取书籍列表，只取前三个
     */
    private suspend fun loadBooksByTagId(tag: BookTag) {
        val result = mModel.getBooksByTag(tag.id)
        val books = result.data
        if (books.size > 2) {
            tag.books = books.subList(0, 3)
        } else {
            tag.books = books
        }
    }

    fun loadTopBooks(): SingleLiveEvent<List<Book>> {
        launchOnIO {
            val result = mModel.getTopBooks()
            topBooksData.postValue(result.data)
        }
        return topBooksData
    }

    fun loadBookByLibId(libId: Int) = createSimpleEvent<List<Book>> {
        val result = mModel.loadBookByLibId(libId)
        result.data
    }
}